package com.wentao.mall.controller;

import com.github.pagehelper.PageInfo;
import com.wentao.mall.commons.Result;
import com.wentao.mall.model.dto.AddCategoryRequest;
import com.wentao.mall.model.dto.UpdateCategoryRequest;
import com.wentao.mall.model.po.Category;
import com.wentao.mall.model.vo.CategoryVo;
import com.wentao.mall.service.CategoryService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.List;

@Validated
@RestController
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @ApiOperation("后台增加产品类别")
    @PostMapping("/admin/category/add")
    public Result addCategory(@RequestBody @Valid AddCategoryRequest addCategoryRequest, HttpSession httpSession){
//        User user = (User)httpSession.getAttribute(Constant.CURRENT_USER);
//        if (user==null){
//            throw new MallException(MallExceptionEnum.NEED_LOGIN);
//        }
//        if (user.getRole().equals(Constant.IS_USER)){
//            throw new MallException(MallExceptionEnum.NEED_ADMIN);
//        }
        Category category=new Category();
        BeanUtils.copyProperties(addCategoryRequest,category);
        categoryService.addCategory(category);
        return Result.success(addCategoryRequest);
    }

    @ApiOperation("后台修改产品类别")
    @PostMapping("admin/category/update")
    public Result updateCategory(@RequestBody @Valid UpdateCategoryRequest updateCategoryRequest){
        //将dto转为po
        Category category=new Category();
        BeanUtils.copyProperties(updateCategoryRequest,category);
        categoryService.updateCategory(category);
        return Result.success("修改成功");
    }

    @ApiOperation("后台删除产品类别")
    @PostMapping("admin/category/delete")
    public Result deleteCategory(@RequestParam(value = "id" ,required = false) @NotNull(message = "id不能为null") Integer id){
        categoryService.deleteCategory(id);
        return Result.success("删除成功");
    }

    @ApiOperation("后台产品类别分页查询")
    @GetMapping("/admin/category/list")
    public Result listForAdmin(@RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum,@RequestParam(value = "pageSize",defaultValue = "10") Integer pageSize){
        PageInfo<Category> pageInfo=categoryService.listForAdmin(pageNum,pageSize);
        return Result.success(pageInfo);
    }

    @ApiOperation("前台商品分类列表")
    @GetMapping("category/list")
    public Result listForCustomer(){
        List<CategoryVo> list = categoryService.listForCusomer();
        return Result.success(list);
    }
}
